﻿using System;
using System.Collections.Generic;
using NHibernate.Criterion;
using SimpleServiceBus.Persistence.Domain.Management.Entities;
using SimpleServiceBus.Persistence.Domain.Management.Repositories;

namespace SimpleServiceBus.Persistence.NHibernate.Repositories
{
    public class EndpointErrorRepository : Repository<EndpointError>, IEndpointErrorRepository
    {

        public IList<EndpointError> FindByEndpoint(ManagedEndpoint endpoint, int? maxResults, DateTime? startDate, DateTime? endDate)
        {
            int topcount = (maxResults == null || maxResults.Value <= 0) ? 100 : maxResults.Value;
            DateTime from = (startDate == null) ? DateTime.Now.AddHours(-24) : startDate.Value;
            DateTime to = (endDate == null) ? DateTime.Now : endDate.Value;

            return FindTopN(topcount, "Timestamp", false, Expression.Eq("ManagedEndpoint", endpoint),
                            Expression.Between("Timestamp", from.ToUniversalTime(), to.ToUniversalTime()));
        }

        public IList<EndpointError> FindAll(int? maxResults, DateTime? startDate, DateTime? endDate)
        {
            int topcount = (maxResults == null || maxResults.Value <= 0) ? 100 : maxResults.Value;
            DateTime from = (startDate == null) ? DateTime.Now.AddHours(-24) : startDate.Value;
            DateTime to = (endDate == null) ? DateTime.Now : endDate.Value;

            return FindTopN(topcount, "Timestamp", false, Expression.Between("Timestamp", from.ToUniversalTime(), to.ToUniversalTime()));
        }
    }
}
